package com.qfly.main.authentication.filter;

import com.qfly.main.authentication.service.CustomUserService;
import com.qfly.main.common.enums.ErrorCodeEnum;
import com.qfly.main.common.utils.JwtTokenUtil;
import com.qfly.main.common.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Wisdytech.cn
 * com.qfly.main.authentication.filter.JwtAuthenticationTokenFilter
 *
 * @author hailin.zhl
 * @date 2018/12/04
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    /**
     * 允许用户可以不带token匿名访问的路径
     */
    private static final String[] allowAnonymousRequestUrl = {"/login","/logout","/favicon.ico","/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**"};

    @Autowired
    CustomUserService customUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Boolean allowAnonymousRequest = false;

        String authHeader = request.getHeader("Authorization");

        // requset with token
        if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")) {
            final String authToken = authHeader.substring("Bearer ".length());

            String username = JwtTokenUtil.parseToken(authToken, "_secret");
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = customUserService.loadUserByUsername(username);
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
            filterChain.doFilter(request, response);
        } else {
            // check is or not allow this request
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            for (String url : allowAnonymousRequestUrl) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    allowAnonymousRequest = true;
                    break;
                }
            }
            // allow Anonymous Request
            if (allowAnonymousRequest) {
                filterChain.doFilter(request, response);
            } else {
                // forbidden
                ResultUtil.sendFail(request,response, ErrorCodeEnum.FORBIDDEN);
            }
        }

    }

}
